-- ExpressMapping
-- Create by weism
-- 级联mapping的操作

-- 设置值
function expressSet(path, dbase, v)
    local arr = string.explode(path, "/");
    if #arr < 1 then error("bad path format."); end
    
    local curr = dbase;
    for i = 1, #arr - 1 do
    repeat
        local step = arr[i];
        if (curr[step] == nil) then
            -- 此路径不存在，需要创建
            curr[step] = {};
            curr = curr[step];
            break; 
        end
            
        local data = curr[step];
        if (type(data) == "table") then
            -- 这是个数值对，继续下一级
            curr = data;
            break;
        end
        
        -- 覆盖数据
        curr[step] = {};
        curr = curr[step]; 
    until true
    end
    
    -- 设置数据
    local last = arr[#arr];
    curr[last] = v;
end

-- 删除一个值
function expressDelete(path, dbase)
    local arr = string.explode(path, "/");
    if (#arr < 1) then error("bad path format.") end
    
    local curr = dbase;
    for i = 1, #arr - 1 do
    	local step = arr[i];
    	if curr[step] == nil then return end
    	
    	curr = curr[step];
    	if (type(curr) ~= "table") then return end
    end
    
    -- 删除数据
    local last = arr[#arr];
    curr[last] = nil;
end

-- 检索数据
function expressQuery(path, dbase, default)
    local arr = string.explode(path, "/");
    local curr = dbase;
    for i = 1, #arr - 1 do
        local step = arr[i];
        curr = curr[step];
        if (curr == nil or type(curr) ~= "table") then return default end
    end
    
    local last = arr[#arr];
    if curr[last] == nil then
        return default;
    else
        return curr[last];
    end
end
